#include "DaterMainMessageCenterWindow.h"
#include "AnimationWindowTrans.h"
#include "DaterDaterWindow.h"
#include "DaterBaseWindowManager.h"

MainMessageCenterWindow::MainMessageCenterWindow(const CEGUI::String& id_name, CEGUI::Window* parent):
MainWindow(parent)
{
	_root = CEGUI::WindowManager::getSingleton().loadWindowLayout("MessageCenterWindow.layout", id_name);

	_name = _root->getName().c_str();

	_root->setVisible(false);

	_root->setClippedByParent(false);

	_parent->addChildWindow(_root);

	subscribeEvents();
}

MainMessageCenterWindow::~MainMessageCenterWindow()
{
	CEGUI::WindowManager::getSingleton().destroyWindow(_root);
}

void MainMessageCenterWindow::showWindow()
{
	RotateTransWindow* rotateTransWindow = new RotateTransWindow(_root, "rot2");
	rotateTransWindow->start();
}

void MainMessageCenterWindow::hideWindow()
{
	_root->deactivate();
	RotateTransWindow* rotateTransWindow = new RotateTransWindow(_root, "rot1");
	rotateTransWindow->start();
}

void MainMessageCenterWindow::subscribeEvents()
{
	using namespace CEGUI;

	WindowManager::getSingleton().getWindow("MessageCenterWindow/MenuBar/BackButton")->subscribeEvent(
		PushButton::EventMouseClick, Event::Subscriber(&MainMessageCenterWindow::handle_back, this));
}

bool MainMessageCenterWindow::handle_back(const CEGUI::EventArgs& args)
{
	static_cast<DaterWindow*>(BaseWindowManager::getSingleton().getWindow("Root"))->backToPreviousWindow();

	return true;
}

void MainMessageCenterWindow::addRequestMessage(RequestMessage* requestMessage)
{
	CEGUI::WindowManager::getSingleton().getWindow("MessageCenterWindow/MessageListArea/MessageList/NoMeesagePromoting")
		->setVisible(false);

	int index = _requestMessages.size();

	MessageWindow* messageWindow = new MessageWindow(index, requestMessage, CEGUI::WindowManager::getSingleton().getWindow(
		"MessageCenterWindow/MessageListArea/MessageList"));
	BaseWindowManager::getSingleton().addBaseWindow(messageWindow);

	_requestMessages.push_back(messageWindow);
}

void MainMessageCenterWindow::removeRequestMeesage(MessageWindow* messageWindow)
{
	std::vector<MessageWindow*>::iterator iter = _requestMessages.begin();
	bool ifFound = false;
	while(iter != _requestMessages.end())
	{
		if((*iter) == messageWindow)
		{
			iter = _requestMessages.erase(iter);
			BaseWindowManager::getSingleton().destroyBaseWindow(messageWindow);

			ifFound = true;
			continue;
		}

		if(ifFound)
		{
			(*iter)->getRoot()->setYPosition(CEGUI::UDim((*iter)->getRoot()->getYPosition().d_scale - 0.15f, 0));
		}
		iter++;
	}
	if(_requestMessages.size() == 0)
	{
		CEGUI::WindowManager::getSingleton().getWindow("MessageCenterWindow/MessageListArea/MessageList/NoMeesagePromoting")
			->setVisible(true);
	}
}

std::vector<MessageWindow*>& MainMessageCenterWindow::getRequestMessageWindows()
{
	return _requestMessages;
}